import { ref, computed, onMounted, onUnmounted, readonly } from 'vue'

// 断点定义
export const BREAKPOINTS = {
  xs: 475,
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
  '2xl': 1536
} as const

export type BreakpointKey = keyof typeof BREAKPOINTS

// 设备类型枚举
export enum DeviceType {
  Mobile = 'mobile',
  Tablet = 'tablet', 
  Desktop = 'desktop'
}

/**
 * 响应式组合式函数
 * 提供屏幕尺寸、设备类型检测和响应式状态管理
 */
export function useResponsive() {
  const screenWidth = ref(0)
  const screenHeight = ref(0)
  
  // 更新屏幕尺寸
  const updateScreenSize = () => {
    screenWidth.value = window.innerWidth
    screenHeight.value = window.innerHeight
  }

  // 设备类型检测
  const deviceType = computed<DeviceType>(() => {
    const width = screenWidth.value
    const userAgent = navigator.userAgent.toLowerCase()
    
    // 基于用户代理和屏幕尺寸综合判断
    if (width < BREAKPOINTS.md || 
        /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(userAgent)) {
      return DeviceType.Mobile
    } else if (width < BREAKPOINTS.xl || 
               /ipad|android.*tablet|kindle|silk/i.test(userAgent)) {
      return DeviceType.Tablet
    } else {
      return DeviceType.Desktop
    }
  })

  // 断点匹配
  const breakpoints = computed(() => ({
    xs: screenWidth.value >= BREAKPOINTS.xs,
    sm: screenWidth.value >= BREAKPOINTS.sm,
    md: screenWidth.value >= BREAKPOINTS.md,
    lg: screenWidth.value >= BREAKPOINTS.lg,
    xl: screenWidth.value >= BREAKPOINTS.xl,
    '2xl': screenWidth.value >= BREAKPOINTS['2xl']
  }))

  // 设备状态
  const isMobile = computed(() => deviceType.value === DeviceType.Mobile)
  const isTablet = computed(() => deviceType.value === DeviceType.Tablet)
  const isDesktop = computed(() => deviceType.value === DeviceType.Desktop)
  const isTouchDevice = computed(() => 'ontouchstart' in window || navigator.maxTouchPoints > 0)

  // 屏幕方向
  const isPortrait = computed(() => screenHeight.value > screenWidth.value)
  const isLandscape = computed(() => screenWidth.value > screenHeight.value)

  // PWA相关
  const isPWA = computed(() => {
    return window.matchMedia('(display-mode: standalone)').matches ||
           window.navigator.standalone === true
  })

  // 安全区域检测
  const safeArea = computed(() => ({
    top: getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-top)') || '0px',
    right: getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-right)') || '0px', 
    bottom: getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-bottom)') || '0px',
    left: getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-left)') || '0px'
  }))

  // 网络连接状态
  const networkStatus = ref<'online' | 'offline'>('online')
  const connectionType = ref<string>('')
  
  const updateNetworkStatus = () => {
    networkStatus.value = navigator.onLine ? 'online' : 'offline'
    
    // @ts-ignore - connection API 还在实验阶段
    if (navigator.connection) {
      // @ts-ignore
      connectionType.value = navigator.connection.effectiveType || ''
    }
  }

  // 视口可见性
  const isVisible = ref(true)
  const updateVisibility = () => {
    isVisible.value = !document.hidden
  }

  // 生命周期管理
  onMounted(() => {
    updateScreenSize()
    updateNetworkStatus()
    updateVisibility()

    window.addEventListener('resize', updateScreenSize)
    window.addEventListener('orientationchange', updateScreenSize)
    window.addEventListener('online', updateNetworkStatus)
    window.addEventListener('offline', updateNetworkStatus)
    document.addEventListener('visibilitychange', updateVisibility)

    // @ts-ignore
    if (navigator.connection) {
      // @ts-ignore
      navigator.connection.addEventListener('change', updateNetworkStatus)
    }
  })

  onUnmounted(() => {
    window.removeEventListener('resize', updateScreenSize)
    window.removeEventListener('orientationchange', updateScreenSize)
    window.removeEventListener('online', updateNetworkStatus)
    window.removeEventListener('offline', updateNetworkStatus)
    document.removeEventListener('visibilitychange', updateVisibility)

    // @ts-ignore
    if (navigator.connection) {
      // @ts-ignore
      navigator.connection.removeEventListener('change', updateNetworkStatus)
    }
  })

  return {
    // 屏幕尺寸
    screenWidth: readonly(screenWidth),
    screenHeight: readonly(screenHeight),
    
    // 设备类型
    deviceType: readonly(deviceType),
    isMobile: readonly(isMobile),
    isTablet: readonly(isTablet),
    isDesktop: readonly(isDesktop),
    isTouchDevice: readonly(isTouchDevice),
    
    // 断点状态
    breakpoints: readonly(breakpoints),
    
    // 屏幕方向
    isPortrait: readonly(isPortrait),
    isLandscape: readonly(isLandscape),
    
    // PWA和安全区域
    isPWA: readonly(isPWA),
    safeArea: readonly(safeArea),
    
    // 网络状态
    networkStatus: readonly(networkStatus),
    connectionType: readonly(connectionType),
    
    // 页面可见性
    isVisible: readonly(isVisible)
  }
}

/**
 * 媒体查询匹配器
 */
export function useMediaQuery(query: string) {
  const matches = ref(false)
  let mediaQuery: MediaQueryList

  const updateMatches = (e: MediaQueryListEvent) => {
    matches.value = e.matches
  }

  onMounted(() => {
    mediaQuery = window.matchMedia(query)
    matches.value = mediaQuery.matches
    
    // 使用新的addEventListener方法
    mediaQuery.addEventListener('change', updateMatches)
  })

  onUnmounted(() => {
    if (mediaQuery) {
      mediaQuery.removeEventListener('change', updateMatches)
    }
  })

  return readonly(matches)
}

/**
 * 断点匹配器
 */
export function useBreakpoint(breakpoint: BreakpointKey) {
  const query = `(min-width: ${BREAKPOINTS[breakpoint]}px)`
  return useMediaQuery(query)
}

/**
 * 暗色主题检测
 */
export function useDarkMode() {
  const prefersDark = useMediaQuery('(prefers-color-scheme: dark)')
  return prefersDark
}

/**
 * 减少动画偏好检测
 */
export function useReducedMotion() {
  const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)')
  return prefersReducedMotion
}

/**
 * 高对比度偏好检测
 */
export function useHighContrast() {
  const prefersHighContrast = useMediaQuery('(prefers-contrast: high)')
  return prefersHighContrast
}

/**
 * 响应式工具函数
 */
export const responsiveUtils = {
  // 根据屏幕尺寸获取网格列数
  getGridColumns: (width: number): number => {
    if (width < BREAKPOINTS.sm) return 1
    if (width < BREAKPOINTS.md) return 2
    if (width < BREAKPOINTS.lg) return 3
    if (width < BREAKPOINTS.xl) return 4
    return 5
  },

  // 根据设备类型获取分页大小
  getPageSize: (deviceType: DeviceType): number => {
    switch (deviceType) {
      case DeviceType.Mobile: return 10
      case DeviceType.Tablet: return 15  
      case DeviceType.Desktop: return 20
      default: return 15
    }
  },

  // 根据屏幕尺寸获取图片尺寸
  getImageSize: (width: number): 'small' | 'medium' | 'large' => {
    if (width < BREAKPOINTS.md) return 'small'
    if (width < BREAKPOINTS.xl) return 'medium'
    return 'large'
  },

  // 判断是否需要懒加载
  shouldLazyLoad: (deviceType: DeviceType): boolean => {
    return deviceType === DeviceType.Mobile
  },

  // 获取触摸手势配置
  getTouchConfig: (isTouchDevice: boolean) => ({
    enableSwipe: isTouchDevice,
    swipeThreshold: isTouchDevice ? 50 : 0,
    tapDelay: isTouchDevice ? 300 : 0
  })
}